<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020/5/22
  Time: 15:55
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>结算页面</title>
    <link rel="stylesheet" href="admin/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="admin/css/font-awesome.min.css"/>
    <link rel="stylesheet" href="admin/css/Lobibox.min.css"/>
    <script src="admin/js/vue.js"></script>
    <script src="admin/js/jquery.min.js"></script>
    <script src="admin/js/bootstrap.min.js"></script>
    <script src="admin/js/jquery.cookie.min.js"></script>
    <script src="admin/js/login-status.js"></script>
    <script src="admin/js/notifications/Lobibox.js"></script>
    <style>
        h4.title {
            font-weight: 800;
        }

        .mgl30 {
            margin-left: 30px;
        }

        #allAddressTable a {
            display: none;
        }

        /** 当鼠标划到 tr上的时候，让它下面的 a标签展示 */
        #allAddressTable tr:hover a {
            display: inline-block;
        }

    </style>
</head>
<body>
<nav class="navbar navbar-default navbar-inverse navbar-static-top">
    <div class="container-fluid">
        <div class="navbar-header">
            <a href="index.jsp" class="navbar-brand" style="color: #ffffff;"><i class="fa fa-sign-language"></i>
                寻欢易购</a>
        </div>
    </div>
</nav>
<div class="container-fluid" id="app">
    <div class="row">
        <div class="col-xs-8 col-xs-push-2">
            <h4 class="title" style="display: inline-block">收货人信息</h4>
            <a data-toggle="collapse" href="#addAddress" id="addMyAddressA" onclick="addAddress()">取消/添加地址</a>
            <div class="collapse form-inline" id="addAddress" style="margin-top: 15px;">
                <div class="form-group">
                    <label for="exampleInputName">名字</label>
                    <input type="text" class="form-control" id="exampleInputName" placeholder="实名" autocomplete="off">
                </div>
                <div class="form-group">
                    <label for="exampleInputAddress">地址</label>
                    <input style="width: 230px" type="email" class="form-control" id="exampleInputAddress"
                           placeholder="国内地址" autocomplete="off">
                </div>
                <div class="form-group">
                    <label for="exampleInputPhone">手机号码</label>
                    <input type="email" class="form-control" id="exampleInputPhone" placeholder="11位手机号码"
                           autocomplete="off">
                </div>
                <input type="button" class="btn btn-success" onclick="yesAddAddress()" value="添加">
            </div>
            <p id="pp" class="alert alert-danger">
                <input type="hidden" id="takeDeliveryAddressId" v-model="defalutTakeDeliveryAddressId">
                <span style="afont-weight: 800;">{{defaultName}}</span>
                <span class="mgl30">{{defaultDetail}}</span>
                <span class="mgl30">{{defaultPhone}}</span>
                <span class="mgl30" ><a href="javascript: void(0);" id="changeTakeDeliveryAddress"
                                       onclick="changeTakeDeliveryAddress(this)">编辑</a></span>
            </p>
            <p class="alert alert-danger" id="changeAddress" hidden>
                <input type="hidden" id="changeDeliveryAddressId" v-model="defalutTakeDeliveryAddressId">
                <input id="defaultStatus" :value="defaultStatus" type="hidden">
                <input id="defaultId" :value="defaultId" type="hidden">
                名字<input id="changeName" :value="defaultName" class="form-control" autocomplete="off">
                地址<input id="changeMyAddress" :value="defaultDetail" class="form-control" autocomplete="off">
                手机<input id="changePhone" :value="defaultPhone" class="form-control" autocomplete="off">
                <input type="button" class="btn btn-danger" value="取消" onclick="noChangeAddress()">
                <input type="button" class="btn btn-success" value="确定" onclick="yesChangeAddress()">
            </p>
            <a data-toggle="collapse" href="#moreAddress" id="moreAddressA">更多地址</a>
            <div class="collapse" id="moreAddress" style="margin-top: 15px;">
                <table id="allAddressTable" class="table">
                    <tr v-for="addr in allAddresses">

                        <td>
                            {{addr.name}} <span class="label label-success" v-if="addr.status == 1">默认</span>
                        </td>
                        <td style="width: 500px">{{addr.detail}}</td>
                        <td>{{addr.phone}}</td>
                        <td><input :value="addr.takeDeliveryStatus" type="hidden">
                            <a href="javascript: void(0);" :aid="addr.id"
                               onclick="deleteTakeDeliveryAddress(this)">删除</a></td>
                        <td style="width: 130px;">
                            <a href="javascript: void(0);" :aid="addr.id"
                               onclick="setTakeDeliveryAddress(this)">设为收货地址</a>

                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-xs-8 col-xs-push-2">
            <h4 class="title">送货清单</h4>
            <table class="table">
                <thead>
                <tr>
                    <td>商品</td>
                    <td>单价</td>
                    <td>数量</td>
                </tr>
                </thead>
                <tbody>
                <tr v-for="g in goods">
                    <td style="max-width: 200px;">
                        <div class="media">
                            <div class="media-left">
                                <a href="javascript: void(0);">
                                    <img class="media-object" height="80px" width="62px" :src="g.imageSrc">
                                </a>
                            </div>
                            <div class="media-body">
                                <h4 class="media-heading">{{g.title}}</h4>
                            </div>
                        </div>
                    </td>
                    <td>{{g.price}}</td>
                    <td>{{g.num}}</td>
                </tr>
                </tbody>
                <tfoot>
                <tr v-if="goods.length != 0" style="text-align: right;">
                    <td colspan="5">
                        总计：￥{{totalPrice}}
                        <button onclick="ensureOrder()" class="btn btn-danger">确认订单</button>
                    </td>
                </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>
<div class="modal" id="payModal" data-backdrop="static">
    <div class="modal-dialog" style="margin-top: 120px;">
        <div class="modal-content">
            <div class="modal-header">
                <button onclick="destoryPayModal()" class="close">
                    <span>&times;</span>
                </button>
                <h3 class="modal-title">支付信息</h3>
            </div>
            <div class="real-name-con margin-tb-25 clearfix">
                <div style="height: 30px"></div>
                <div class="content-right-zoon">
                    &nbsp;&nbsp;&nbsp;&nbsp;<span style="font-size: large; color: #933EC5">支付类型：</span>
                    <input id="zfb" name="pay" checked value="1"  type="radio"> <label for="zfb"><img style="height: 30px" src="images/zfb.png">&nbsp;<img style="height: 16px" src="images/tuijian.png"></label>
                    <input id="wx" name="pay"  value="2" type="radio" style="margin-left: 20px;"> <label for="wx"><img style="height: 30px" src="images/wx.png"></label>

                </div>
            </div>
            <div class="modal-body">
                <input type="hidden" id="orderNo">
                <h4 style="font-weight: 800;"><span>应付金额: </span>￥<span style="color: red;" id="totalPrice"></span></h4>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" onclick="destoryPayModal()">取消支付</button>
                <button type="button" onclick="toAliPay()" class="btn btn-success">去支付</button>
                <%--                <button type="button" onclick="confirmPay()" class="btn btn-success">确认支付</button>--%>
            </div>
        </div>
    </div>
</div>
</body>
<script>
    //添加地址操作-取消
    function addAddress() {
        $('#exampleInputName').val(""); //获取名字
        $('#exampleInputAddress').val(''); //获取地址
        $('#exampleInputPhone').val(''); //获取
        $("#changeTakeDeliveryAddress").html('编辑').toggle()
        $("#moreAddressA").html('更多地址').toggle()

    }

    //确定添加地址
    function yesAddAddress() {
        var name = $('#exampleInputName').val(); //获取名字
        var address = $('#exampleInputAddress').val(); //获取地址
        var phone = $('#exampleInputPhone').val(); //获取
        //验证手机号是否为11位
        var reg = /^1(44|47|91|99|73|76|77|[358]\d)\d{8}$/;
        if (!reg.test(phone)) {
            showErrorBox('请填写正确手机号码.')
            return;
        }
        $.ajax({
            url: '${pageContext.servletContext.contextPath}/addressServlet/addAddress',
            type: 'get',
            data: {name: name, address: address, phone: phone},
            dataType: 'json',
            success: function (_data) {
                if (_data.length > 0) {
                    showErrorBox('添加成功');
                } else {
                    showErrorBox('添加失败');
                }

            }
        })
        window.location.href = 'settleCount.jsp';
    }

    var vm = new Vue({
        el: '#app',
        data: {
            defalutTakeDeliveryAddressId: 0,
            defaultDetail: '',    //默认详情信息
            defaultName: '',       //默认的名字
            defaultPhone: '',      // 默认电话
            defaultStatus: '',      // 默认Status
            defaultId: '',      // 默认id
            defaulTakeDeliveryStatus: '',      // 默认takeDeliveryStatus
            allAddresses: [],     //其他的地址信息
            goods: [],
            totalPrice: 0
        }
    })

    // 获取地址
    function getAddress() {
        $.ajax({
            url: '${pageContext.servletContext.contextPath}/addressServlet/getAddressOfUser',
            type: 'get',
            // data: {method: 'getAddressOfUser'},
            dataType: 'json',
            success: function (_data) {
                vm.allAddresses = [];
                for (var i = 0; i < _data.length; i++) {
                    var addr = _data[i];  //取到每个地址
                    vm.allAddresses.push(addr);
                    if (addr.takeDeliveryStatus == 1) {  // 收货地址
                        vm.defalutTakeDeliveryAddressId = addr.id; //设置默认收货地址的id
                        vm.defaultDetail = addr.detail;
                        vm.defaultName = addr.name;
                        vm.defaultPhone = addr.phone;
                        vm.defaultStatus = addr.status;
                        vm.defaultId = addr.id;
                    }
                }
            }
        })
    }

    var totalPrice = 0;

    function getGoodsInfo() {
        // 转换为json数据: {'1001': 1, '1002': 2}
        var localShoppingCart = JSON.parse(localStorage.getItem('local_shopping_cart'));
        var goodIds = Object.keys(localShoppingCart); //取到所有的商品的id, 返回值为数组：['1001', '1002']

        // join(‘,’) 只用指定的字符将数组拼接成字符串
        var goodIdsStr = goodIds.join(','); // ['1001', '1002', '1003'] -> 1001,1002,1003

        $.ajax({
            url: '${pageContext.servletContext.contextPath}/cart',
            type: 'post',
            dataType: 'json',
            data: {ids: goodIdsStr},
            success: function (_data) {  // [{}, {}, {}]
                totalPrice = 0;
                for (var i = 0; i < _data.length; i++) {
                    var good = _data[i];  //获取到每件商品
                    var goodId = good.goodId; //获取商品的id, 目的是获取商品的数量
                    // 动态的添加的属性, 购买的商品数量
                    good.num = localShoppingCart['' + goodId];

                    totalPrice += (good.num * good.price); //计算总的价格
                    vm.goods.push(good);
                }
                vm.totalPrice = totalPrice;
            }
        })
    }

    getAddress();  //获取收货地址
    getGoodsInfo(); //获取商品信息

    //设置当前地址为收货地址
    function setTakeDeliveryAddress(aTag) {
        var currentAddressId = $(aTag).attr('aid'); //获取当前地址的id

        $.ajax({
            url: '${pageContext.servletContext.contextPath}/addressServlet/changeTakeDeliveryAddress',
            data: {addressId: currentAddressId},
            dataType: 'json',
            type: 'get',
            success: function (_data) {
                if (_data.code > 0) {  //更新收货地址成功
                    getAddress();  //重新获取地址信息
                } else {
                    console.log(_data.msg)
                }
            }
        })
    }

    //删除当前收货地址
    function deleteTakeDeliveryAddress(aTag) {
        var currentAddressId = $(aTag).attr('aid'); //获取当前地址的id
        var inputVal=$(aTag).parent().children('input').val();
        if (inputVal=="1"){
            showErrorBox('当前为收货地址不能删除!')
            return;
        }else {
            $.ajax({
                url: '${pageContext.servletContext.contextPath}/addressServlet/deleteAddress',
                data: {addressId: currentAddressId},
                dataType: 'json',
                type: 'get',
                success: function (_data) {
                    if (_data.code > 0) {  //更新收货地址成功
                        getAddress();  //重新获取地址信息
                    } else {
                        console.log(_data.msg)
                    }
                }
            })
        }

    }

    //显示编辑当前收货地址页面
    function changeTakeDeliveryAddress() {
        $("#changeAddress").show()
        $("#addMyAddressA").html('')
        $("#moreAddressA").html('')
    }

    function noChangeAddress() {
        $("#changeAddress").hide()
        $("#addMyAddressA").html('添加地址')
        $("#moreAddressA").html('更多地址')
    }
    function yesChangeAddress() {
        $("#changeAddress").hide()
        var name = $('#changeName').val(); //获取名字
        var address = $('#changeMyAddress').val(); //获取地址
        var phone = $('#changePhone').val(); //获取
        var defaultStatus = $('#defaultStatus').val(); //获取
        var defaultId = $('#defaultId').val(); //获取
        //验证手机号是否为11位
        var reg = /^1(44|47|91|99|73|76|77|[358]\d)\d{8}$/;
        if (!reg.test(phone)) {
            showErrorBox('请填写正确手机号码.')
            return;
        }

        $.ajax({
            url: '${pageContext.servletContext.contextPath}/addressServlet/changeDefalutAddress',
            data: {name:name,address:address,phone:phone,defaultStatus:defaultStatus,defaultId:defaultId},
            dataType: 'json',
            type: 'post',
            success: function (_data) {
                if (_data.code > 0) {  //更新收货地址成功
                    getAddress();  //重新获取地址信息
                } else {
                    console.log(_data.msg)
                }
            }
        })

        $("#moreAddressA").html('更多地址')
        $("#addMyAddressA").html('添加地址')
    }

    // 点击 "确认订单"，去支付
    function ensureOrder() {
        var localShoppingCartData = localStorage.getItem('local_shopping_cart'); // {1001: 2, 1002:1}
        var defalutTakeDeliveryAddressId = $('#takeDeliveryAddressId').val();

        // console.log(localShoppingCartData, defalutTakeDeliveryAddressId)
        /**
         * 1. 将所有的商品生产订单。
         * 2. 展示模态框开始支付。
         */
        $.ajax({
            url: '${pageContext.servletContext.contextPath}/order/ensureOrder',
            type: 'post',
            dataType: 'json',
            data: {
                goodsInfo: localShoppingCartData,
                takeDelivertyAddressId: defalutTakeDeliveryAddressId,
                method: 'ensureOrder'
            },
            success: function (_data) {
                // 生成订单成功
                if (_data.code > 0) {
                    // 删除用户的本地购物车数据
                    localStorage.removeItem('local_shopping_cart');
                    $('#totalPrice').html(_data.obj.totalPrice);
                    $('#orderNo').val(_data.obj.orderNo);
                    $('#payModal').modal('show');
                } else {
                    showErrorBox(_data.msg);
                }
            }
        })
    }

    //选择支付方式
    function toAliPay(){
        var pay=$("input[name='pay']:checked").val();
        var orderNo = $('#orderNo').val();
        // 支付宝支付：创建form表单，以json格式传四个参数
        switch (pay){
            case '1':
                // localStorage.setItem("orderNo",orderNo);
                // localStorage.setItem("totalPrice",totalPrice);
                // location.href="alipay.trade.page.pay.jsp";
                var aipay = document.createElement("form");
                aipay.action = "alipay.trade.page.pay.jsp";
                aipay.method = "post";
                aipay.style.display = "none";
                var PARAMS = {
                    "WIDout_trade_no": orderNo,
                    "WIDsubject": "Living Goods",
                    "WIDtotal_amount": totalPrice,
                    "WIDbody": "XunHuanShop"
                }
                for (var x in PARAMS) {
                    var opt = document.createElement("textarea");
                    opt.name = x;
                    opt.value = PARAMS[x];
                    aipay.appendChild(opt);
                }
                document.charset='utf-8';
                document.body.appendChild(aipay);
                aipay.submit();
                break;
            // 微信支付
            case '2':
                localStorage.setItem("orderNo",orderNo);
                localStorage.setItem("totalPrice",totalPrice);
                location.href="wxpay.html";
                break;
        }
    }

    // 确认支付, 总金额要从后台这边查询，将订单id传入到后台
    <%--function confirmPay() {--%>
    <%--    var orderNo = $('#orderNo').val(); //获取订单编号--%>
    <%--    $.ajax({--%>
    <%--        url: '${pageContext.servletContext.contextPath}/order',--%>
    <%--        dataType: 'json',--%>
    <%--        type: 'post',--%>
    <%--        data: {orderNo: orderNo, method: 'confirmPay'},--%>
    <%--        success: function (_data) {--%>
    <%--            $('#payModal').modal('hide');--%>
    <%--            // 支付成功--%>
    <%--            if (_data.code > 0) {--%>
    <%--                location.href = 'showOrder.jsp';--%>
    <%--            } else { //支付失败--%>
    <%--                showErrorBox(_data.msg)--%>
    <%--            }--%>
    <%--        }--%>
    <%--    })--%>
    <%--}--%>

    // 关闭支付模态框
    function destoryPayModal() {
        $('#payModal').modal('hide');
        location.href = 'showOrder.jsp';
    }

    // 显示错误提示信息
    function showErrorBox(msgText) {
        Lobibox.notify('warning', {
            size: 'mini',
            delay: 2000,
            delayIndicator: false,
            title: false, //不给title
            msg: msgText,
            sound: false  // 不要音频
        })
    }
</script>
</html>
